<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :rules="rules" :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="120px">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="开始年份:" prop="ksNf">
            <el-input v-model="queryParams.ksNf" placeholder="请输入开始年份" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结束年份:" prop="jsNf">
            <el-input v-model="queryParams.jsNf" placeholder="请输入结束年份" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称:" prop="xmName">
            <el-input v-model="queryParams.xmName" placeholder="请输入项目名称" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格数据为空时 -->
    <div v-if="zzZeList.length == 0"
         style="width: 100%; height: 70vh;display: flex;align-items: center;justify-content:center;">
      <div
        style="margin: auto;display: flex;flex-direction: column;align-items: center;justify-content:center;position: relative">
        <img src="../../../assets/images/data.png" style="width: 130px;" alt="">
        <div style="color: #cccccc;font-size: 18px;">请输入开始年份、结束年份、项目名称进行查询</div>
      </div>
    </div>

    <!-- 表格数据不为空时 -->
    <el-table v-if="zzZeList.length != 0" :data="zzZeList" height="600"
              show-summary sum-text="汇总" :summary-method="getSummaries" class="fixedTableOne"
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}">
      <el-table-column label="序号" align="center" type="index"/>
      <el-table-column label="项目名称" align="center" prop="xmName">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.xmName }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="所属单位" align="center" prop="ssDw"></el-table-column>
      <el-table-column label="项目编号" align="center" prop="xmBh"></el-table-column>
      <el-table-column label="开始时间" align="center" prop="ksTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ksTime, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="jsTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jsTime, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目总额" align="center" prop="xmZe"></el-table-column>
      <el-table-column align="center"
                       v-for="year in dynamicYears"
                       :key="year"
                       :label="year + '载账金额'"
                       :prop="`yearAmountMap.${year}`">
        <template slot-scope="scope">
          <!-- Check if yearAmountMap exists before rendering -->
          {{ scope.row.yearAmountMap ? scope.row.yearAmountMap[year] : 'N/A' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 流水填报查看 -->
    <LsTbXq ref="lsTbXq"/>
  </div>
</template>

<script>
import {selectZzZeList} from "@/api/fztz/zzze";
import LsTbXq from "@/views/fztz/lstb/components/LsTbXq.vue";

export default {
  name: "ZzZeCx",
  components: {LsTbXq},
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      zzZeList: [],
      // 查询参数
      queryParams: {
        ksNf: null,
        jsNf: null,
        xmName: null
      },
      // 表单校验
      rules: {
        ksNf: [{required: true, message: "开始年份不能为空", trigger: "blur"},
          {pattern: /^(19|20)\d{2}$/, message: "请输入有效的年份", trigger: "blur"}],
        jsNf: [{required: true, message: "结束年份不能为空", trigger: "blur"},
          {pattern: /^(19|20)\d{2}$/, message: "请输入有效的年份", trigger: "blur"}],
        xmName: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
      },

    }
  },
  computed: {
    // 提取所有年份并排序（如果需要）
    dynamicYears() {
      // Make sure zzZeList is not empty and the first item contains yearAmountMap
      if (this.zzZeList.length > 0 && this.zzZeList[0].yearAmountMap) {
        const years = Object.keys(this.zzZeList[0].yearAmountMap); // 提取年份
        return years.sort((a, b) => a - b); // 可选：按年份排序
      }
      return [];
    }
  },
  created() {

  },
  methods: {
    //打开流水填报详情
    handleButtonClick(row) {
      this.$refs.lsTbXq.handleOpen(row)
    },
    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '汇总'; // 第一列显示为'汇总'
          return;
        }

        // Check if the column is related to 'yearAmountMap'
        if (column.property.startsWith('yearAmountMap.')) {
          const year = column.property.split('.').pop(); // 获取年份
          const values = data.map(item => {
            return item.yearAmountMap ? Number(item.yearAmountMap[year]) : NaN; // 获取该年份的值
          });

          if (!values.every(value => isNaN(value))) {
            // 对年金额列进行求和
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              return !isNaN(value) ? prev + value : prev;
            }, 0);
            sums[index] = sums[index].toString(); // 将结果转换为字符串显示
          } else {
            sums[index] = '---'; // 如果该列没有有效数据
          }
        } else {
          sums[index] = ''; // For non 'yearAmountMap' columns, no sum
        }
      });

      return sums;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.$refs["queryForm"].validate(valid => {
        if (valid) {
          this.getList();
        }
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.xmName = null
      this.zzZeList = []
    },
    getList() {
      // 打开遮罩层
      this.$modal.loading("正在获取数据，请稍后...");
      selectZzZeList(this.queryParams.ksNf, this.queryParams.jsNf, this.queryParams.xmName).then(res => {
        this.zzZeList = res.data
        if (this.zzZeList.length == 0) {
          this.$modal.alertWarning("无该项目, 请重新查询");
        }
        // 关闭遮罩层
        this.$modal.closeLoading();
      })
    },

  }
}
</script>

<style scoped>

</style>
